package com.qian2.pricesharingapplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.lb2.JSONParser;
import com.example.pricesharingapplication.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.qian2.pricesharingapplication.AllProductsActivity.LoadAllProducts;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SearchProduct extends ListActivity {

	public boolean isOnline() {
		ConnectivityManager cm =
				(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	private Spinner spinner1, spinner2;
	private EditText contentTxt;
	private EditText contentTxt2;
	private Button btnSubmit;
	private Button btnScan;
	private int position;

	// Progress Dialog
	private ProgressDialog pDialog;
	public static final String Email = "emailKey";

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();


	// url to get all products list
	private static String url_search_products = "http://wwwfyp.cse.ust.hk:7117/search_name.php";
	private static String url_search_uid = "http://wwwfyp.cse.ust.hk:7117/search_product.php";
	// JSON Node names
	
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_PRODUCTS = "product";
	private static final String TAG_UID = "uid";
	private static final String TAG_upc = "upc";
	private static final String TAG_ID = "categoryID";
	private static final String TAG_NAME = "name";
	private static final String TAG_BRAND = "brand";	
	private static final String TAG_description = "description";
	// products JSONArray
	JSONArray products = null;
	private EditText itemname;
	String scanContent="";
	String findUid="";
	Boolean refreshing=false;
	int success =0;
	
	ArrayList<String> product_list = new ArrayList<String>();
	private MainArrayAdapter madapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		((MainActivity) getParent()).temp(this);

		contentTxt = (EditText)findViewById(R.id.barcode);
		itemname = (EditText)findViewById(R.id.editText2);
		//listen for clicks
		
		addListenerOnButton();
		addListenerOnSpinnerItemSelection();
		itemname.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if (!itemname.toString().equals(""))
					if(isOnline()){
						product_list.clear();
						creatlist();						
					}
			}
			
		});
		
	}

	private void creatlist() {
		if (refreshing) return;
		else refreshing=true;

		
		// Loading products in Background Thread
		new GetSearchDetails().execute();

		// Get listview
		ListView lv = getListView();
		// on seleting single product
		// launching Edit Product Screen
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem

				String uid = ((TextView) view.findViewById(R.id.uid)).getText()
						.toString();
							
				if (!uid.equals("Server_error") && !uid.equals("No_network")){
					// Starting new intent
					Intent in = new Intent(getApplicationContext(),
							ProductPage.class);
					// sending upc to next activity
					
					in.putExtra(TAG_UID, uid);

					

					Log.d("SearchProduct :", in.getStringExtra("uid"));					
					// starting new activity and expecting some response back
//					Toast.makeText(parent.getContext(), 
//							"OnItemSelectedListener : " + parent.getItemAtPosition(position).toString(),
//							Toast.LENGTH_LONG).show();
					
					startActivityForResult(in, 100);
					// startActivityForResult(new Intent(SearchProduct.this, ProductPage.class), 1);
					
				}
			}
		});
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// if result code 100
		if (resultCode == 100) {
			// if result code 100 is received 
			// means user edited/deleted product
			// reload this screen again
			Intent intent = getIntent();
			finish();
			startActivity(intent);
		}

	}
	

	public void addListenerOnSpinnerItemSelection() {
		spinner1 = (Spinner) findViewById(R.id.spinner1);
		spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
			@Override
			  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
				product_list.clear();
				creatlist();
					Toast.makeText(parent.getContext(), 
						"Selected:"+parent.getSelectedItemPosition()+" "+ parent.getItemAtPosition(pos).toString(),
						Toast.LENGTH_SHORT).show();
				  }

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
		
	}

	// get the selected dropdown list value
	public void addListenerOnButton() {

		spinner1 = (Spinner) findViewById(R.id.spinner1);
		
	}

	class GetSearchDetails extends AsyncTask<String, String, String> {

		private ProgressDialog pDialog;
		


		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
//			pDialog = new ProgressDialog(SearchProduct.this);
//			pDialog.setMessage("Loading product details. Please wait...");
//			pDialog.setIndeterminate(false);
//			pDialog.setCancelable(true);
//			pDialog.show();
		}

		/**
		 * Getting product details in background thread
		 * */
		protected String doInBackground(String... args) {

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			System.out.println("iteamname:"+itemname.getText().toString());
			position=spinner1.getSelectedItemPosition();
			System.out.println("position= "+position);
			params.add(new BasicNameValuePair("name", itemname.getText().toString()));
			params.add(new BasicNameValuePair("catID", Integer.toString(position)));
			// getting JSON string from URL
			//File file = new File(productlistlocalurl);
			JSONObject json=null;
			if(isOnline())
				json = jParser.makeHttpRequest(url_search_products, "GET", params);
			if (isOnline()) Log.d("Search Response Json: ", json.toString());
			//System.out.println(json);
			try {
				// Checking for SUCCESS TAG
				success =0;
				if (isOnline() && json!=null){
					success = json.getInt(TAG_SUCCESS);
					if (success == 1 ) {
						// products found
						// Getting Array of Products
						products = json.getJSONArray(TAG_PRODUCTS);
						

						// looping through All Products
						for (int i = 0; i < products.length(); i++) {
							JSONObject c = products.getJSONObject(i);

							// Storing each json item in variable
							String uid = c.getString(TAG_UID);
							String brand = c.getString(TAG_BRAND);
							String name = c.getString(TAG_NAME);

							product_list.add(i + " ### " + uid + " ### " + brand + " ### " + name+ " ### " + "http://wwwfyp.cse.ust.hk:7117/Picture/upload/"+uid+"/"+uid+".jpg");
						}
					}
				} else if (!isOnline()){
					String brand = "No_network";		
					String uid = "0";
					String name = " ";
					product_list.add(1 + " ### " + uid + " ### " + brand + " ### " + name+ " ### " + R.drawable.ic_action_warning);
				} 				
				else {				
					String brand = "Server_error";					
					String uid = "0";
					String name = " ";					
					product_list.add(1 + " ### " + uid + " ### " + brand + " ### " + name+ " ### " + R.drawable.ic_action_warning);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				
			}
			
			



			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once got all details
			//pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					
					Log.d("Search textchanged finished: ", "");

					
					int temp=R.drawable.ic_action_picture;
//					if (success!=1)
//						temp =R.drawable.ic_action_warning;

					madapter = new MainArrayAdapter(SearchProduct.this, product_list,temp){					
						@Override
						public View getView(int position, View convertView,
								ViewGroup parent) {
							// TODO Auto-generated method stub
							View view= super.getView(position, convertView, parent);

							Button button=(Button) view.findViewById(R.id.report_price_button);
							button.setOnClickListener(new OnClickListener(){

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									// TODO Auto-generated method stub
									if(!MainActivity.sharedpreferences.contains(Email)){
										Intent in2 = new Intent(getApplicationContext(),
												ChooseAccount.class);
										startActivityForResult(in2, 90);
										
									}
									else{
										Intent in = new Intent(SearchProduct.this,QuotationActivity.class);
										// sending upc to next activity
										in.putExtra(TAG_UID, (CharSequence) ((TextView)((View) v.getParent()).findViewById(R.id.uid)).getText().toString());
										in.putExtra(TAG_NAME, (CharSequence) ((TextView)((View) v.getParent()).findViewById(R.id.name)).getText().toString());
										startActivityForResult(in, 100);
									}
								}

							});
							return view;
						}

					};
					setListAdapter(madapter);
					refreshing=false;
				}
			});

		}
	}
	class GetUid extends AsyncTask<String, String, String> {

		private ProgressDialog pDialog;
		


		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}
		/**
		 * Getting product details in background thread
		 * */
		protected String doInBackground(String... args) {

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();			
			params.add(new BasicNameValuePair("upc", scanContent));
			JSONObject json=null;
			json = jParser.makeHttpRequest(url_search_uid, "GET", params);
			Log.d("Search Response Json: ", json.toString());
			//System.out.println(json);
			try {
				// Checking for SUCCESS TAG
				int success =0;
				if (isOnline() && json!=null){
					success = json.getInt(TAG_SUCCESS);
					if (success == 1 ) {
						// products found
						// Getting Array of Products
						products = json.getJSONArray(TAG_PRODUCTS);
						

						// looping through All Products
						for (int i = 0; i < products.length(); i++) {
							JSONObject c = products.getJSONObject(i);

							// Storing each json item in variable
							findUid = c.getString(TAG_UID);
						

							
							
						}
					}
				} else if (!isOnline()){
					// Storing each json item in variable
					 findUid = "No_network";
					//String description = c.getString(TAG_description);
	
				} 				
				else {
					// Storing each json item in variable
					findUid = "Server_error";
					//String description = c.getString(TAG_description);

					// creating new HashMap
									}
			} catch (JSONException e) {
				e.printStackTrace();
				
			}
			
			

			
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once got all details
			//pDialog.dismiss();
			if (!findUid.equals("Server_error") && !findUid.equals("No_network")){
				// Starting new intent
				if(!findUid.isEmpty()){
				Intent in = new Intent(getApplicationContext(),
						ProductPage.class);
				// sending uid to next activity
				
				in.putExtra(TAG_UID, findUid);
				
				startActivityForResult(in, 110);
				}
				else{
					Toast toast = Toast.makeText(getApplicationContext(), 
							"No products found!", Toast.LENGTH_SHORT);
					toast.show();
				}
			}

		}
	}
		
}

